/*
 * Copyright (c) 2022.版权所有高金磊
 */

package 领扣算法.AA中等题.连接两字母单词得到的最长回文串;

import java.util.HashMap;

public class Main {
    public int longestPalindrome(String[] words) {
        int res=0;
        HashMap<String,Integer> data2=new HashMap<>();
        for (String word : words) {
            char[] middle=word.toCharArray();
            data2.put(word,data2.getOrDefault(word, 0)+1);
        }
        for (String s : data2.keySet()) {
            char[] middle=s.toCharArray();
            String s_re=""+middle[1]+middle[0];
            if (!s.equals(s_re)) {
                if (!data2.containsKey(s_re) || data2.get(s_re) == 0) {
                    continue;
                }
                int min = Math.min(data2.get(s), data2.get(s_re));
                res += 4*min;
                data2.put(s, 0);
                data2.put(s_re, 0);
            }else {
                int min =data2.get(s)/2;
                res+=min*4;
                data2.put(s, data2.get(s)-min*2);

            }
        }
        for (String s : data2.keySet()) {
            if (s.charAt(0)==s.charAt(1)&&data2.get(s)!=0){
                return res+2;
            }
        }
        return res;

    }
}
